#!/bin/bash

# ===========================================================================
# File: "updateAlphaTcl"
#                        Created: 2018-07-08 10:05:06
#              Last modification: 2019-10-02 17:07:11
# Author: Bernard Desgraupes
# e-mail: <bdesgraupes@users.sourceforge.net>
# Copyright (c) 2018-2019 Alpha Cabal
# All rights reserved.
# This file is part of the AlphaCocoa project.
# ===========================================================================

UA_VERSION="0.1"
UA_NAME=$(basename $0)

UA_SVN_BASE=svn.code.sf.net/p/alphacocoa/code

UA_PRINT_LOG=1
UA_DEVELOPER=0
UA_CLEANUP=1
UA_SFUSER_NAME=

printusage () {
	echoinfo "Usage:"
	echo "  $UA_NAME [-d] [-u name] [-x] ?appPath?"
	echo "  $UA_NAME [-h|-v]"
	echoinfo "Options:"
	echo "  -d         developer checkout/update"
	echo "  -h         print usage"
    echo "  -u         user name at SourceForge"
    echo "  -v         print version number"
    echo "  -x         no cleanup"
	echo "If -u specified, use the svn+ssh protocol (safer and faster)."
	echo "If appPath not specified, default is '/Applications/Alpha.app'."
	echoinfo "Examples:"
	echo "  $UA_NAME"
	echo "  $UA_NAME -d"
	echo "  $UA_NAME -d -u vhugo"
	echo "  $UA_NAME -d /path/to/Alpha.app"
}

echoerror () {
	echo -e "\033[1;31m$1\033[0m"
}

echowarn () {
	echo -e "\033[1;33m$1\033[0m"
}

echoinfo () {
	echo -e "\033[1;36m$1\033[0m"
}

echocaution () {
	echo -e "\033[1;35m$1\033[0m"
}

cleanup () {
	if [ $UA_CLEANUP == 1 ] ; then
		if [ -e $UA_TEMP_DIR ] ; then
			echoinfo "* removing temp dir"
			cd $UA_TEMP_DIR
			rm -rf *
			rm -rf ./.svn
			rmdir $UA_TEMP_DIR
		fi
	fi
}

rmTclIndex () {
	cd $UA_APP_ALPHATCL/Tcl/SystemCode
	echoinfo "* removing tclIndex files from SystemCode dir"
	rm -rf tclIndex
}

suggestRestart () {
	UA_ALPHA_PID=`ps -x -o pid,command | grep -E "\\d+ ${UA_APP_PATH}" | awk '{print $1}'`
	if [ "$UA_ALPHA_PID" != "" ] ; then
		echocaution ">>>>"
		echocaution ">>>> Restart of Alpha is highly recommended."
		echocaution ">>>>"
	fi
}

# Parse the command line options
while getopts ":dhu:vx" opt; do
	case $opt in
		d )
			UA_DEVELOPER=1;;
		h )
			echo $UA_NAME "- version $UA_VERSION" 
			echo "Copyright (c) `date "+%Y"`, Bernard Desgraupes"
			echo "Checkout AlphaTcl inside Alpha's application bundle."
			echo "This script is an extra tool for the Alpha Text Editor:"
			echo "  <https://alphacocoa.sourceforge.io/>"
			printusage 
			exit 0 ;;
		u )
			UA_SFUSER_NAME=$OPTARG
			;;
		v )
			echo $UA_VERSION 
			exit 0 ;;
		x )
			UA_CLEANUP=0
			;;
		\? )
			echo "Unknown option."
			printusage
			exit 1 ;;
	esac
done

if ! [ -e $UA_LOG_DIR ] ; then
	mkdir -p $UA_LOG_DIR
fi

# Skip the processed options
shift $((--OPTIND))

if [ $# == 0 ] ; then
	echowarn "missing path of application -> assuming /Applications/Alpha.app"
	UA_APP_PATH="/Applications/Alpha.app"
else
	UA_APP_PATH="${!#}"
fi

UA_APP_ALPHATCL=${UA_APP_PATH}/Contents/Resources/Libraries/AlphaTcl
if ! [ -e $UA_APP_ALPHATCL ] ; then
	echoerror "can't find $UA_APP_ALPHATCL"
	exit 1
fi

if [ $UA_DEVELOPER == 0 ] ; then
	# This is a user update
	UA_SVN_SUBCMD=export
else
	if [ -e $UA_APP_ALPHATCL/.svn ] ; then
		# This is a developer update
		UA_SVN_SUBCMD=update
	else
		# This is a developer checkout
		UA_SVN_SUBCMD=checkout
	fi
fi

# Check svn availability
UA_SVN_CMD=`which svn`
if [ "$UA_SVN_CMD" == "" ] ; then
	echoerror "can't find svn tool"
	exit 1
fi

# ================
# Developer Update
# ================
if [ $UA_SVN_SUBCMD == "update" ] ; then
	echoinfo "* performing ${UA_SVN_SUBCMD}..."	
	cd $UA_APP_ALPHATCL
	# Run cleanup in case there are locks
	$UA_SVN_CMD cleanup
	$UA_SVN_CMD $UA_SVN_SUBCMD
# 	if [ $? == 0 ] ; then
# 		rmTclIndex
# 	fi
	suggestRestart
	exit 0
fi


# =======================
# User/Developer Checkout
# =======================
# Create a temporary dir
UA_TEMP_DIR=`mktemp -d -t alphatcl_svn`
if [ $? -ne 0 ]; then
	echoerror "can't create temp dir"
	exit 1
else
	echoinfo "* creating temp dir..."	
	echo "$UA_TEMP_DIR"	
fi

# Build the URL of the repository
if [ "$UA_SFUSER_NAME" == "" ] ; then
	UA_SVN_REPO=https://$UA_SVN_BASE
else
	UA_SVN_REPO=svn+ssh://$UA_SFUSER_NAME@$UA_SVN_BASE
fi

# Checkout the library
echoinfo "* performing ${UA_SVN_SUBCMD}..."	
cd $UA_TEMP_DIR
$UA_SVN_CMD $UA_SVN_SUBCMD --force $UA_SVN_REPO/Current/Libraries/AlphaTcl 
if [ $? -ne 0 ]; then
	echoerror "...$UA_SVN_SUBCMD failed"
	cleanup
	exit 1
else
	echo "...done"
fi

# Check rsync availability
UA_RSYNC_CMD=`which rsync`
if [ "$UA_RSYNC_CMD" == "" ] ; then
	echoerror "can't find rsync tool"
	exit 1
fi

# Synchronize the library
UA_TEMP_ALPHATCL=$UA_TEMP_DIR/AlphaTcl
if [ -e $UA_TEMP_ALPHATCL ] ; then
	cd $UA_TEMP_ALPHATCL
	UA_TEMP_SUBDIRS=`find . -type d -mindepth 1 -maxdepth 1 -print | sed 's:./::' | sort`
	echoinfo "* synchronizing AlphaTcl in application bundle..."
	for sub in $UA_TEMP_SUBDIRS; do
		echoinfo "> $sub dir"	
		if [ $sub == ".svn" ] ; then
			if [ -e ${UA_APP_ALPHATCL}/.svn ] ; then
				rm -rf ${UA_APP_ALPHATCL}/.svn
			fi
			mv ${UA_TEMP_ALPHATCL}/.svn ${UA_APP_ALPHATCL}/.svn
		else
			if [ $sub == "Help" ] ; then
				UA_RSYNC_OPTS="-auv"
			else
				UA_RSYNC_OPTS="-auv --delete --force-delete"
			fi
			$UA_RSYNC_CMD $UA_RSYNC_OPTS ${UA_TEMP_ALPHATCL}/$sub/ ${UA_APP_ALPHATCL}/$sub
			if [ $? != 0 ] ; then
				echoerror "synchronization of $sub dir failed"
				cleanup
				exit 1
			fi
			
		fi
	done	
else
	echoerror "can't find exported AlphaTcl - synchronization failed"
	cleanup
	exit 1
fi

# Delete the temp dir (unless option -x was set)
cleanup	

# Suggest restart if Alpha is running
# echoinfo "* Restarting Alpha..."
suggestRestart

exit 0
